<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-date"></i> 权限管理</el-breadcrumb-item>
                <el-breadcrumb-item>用户设置</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="search_block">
                <el-collapse v-model="activeNames">
                    <el-collapse-item name="1">
                        <template slot="title">
                            <i class="el-icon-search"></i> 筛选查询
                        </template>
                        <el-row>
                            <el-col :span="2" class="pleft">
                                <span>输入搜索：</span>
                            </el-col>
                            <el-col :span="3">
                                <el-input v-model="searchKey" placeholder="姓名"></el-input>
                            </el-col>
                            <el-col :span="2">
                                <span>主管姓名：</span>
                            </el-col>
                            <el-col :span="3">
                                <el-select v-model="managerId2" placeholder="请选择主管" clearable>
                                    <el-option
                                        v-for="item in manageValue"
                                        :key="item.userId"
                                        :label="item.userName"
                                        :value="item.userId"
                                    ></el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="2">
                                <span>职责：</span>
                            </el-col>
                            <el-col :span="3">
                                <el-select v-model="dutyId2" placeholder="请选择职责" clearable>
                                    <el-option
                                        v-for="item in dutyList"
                                        :key="item.rowId"
                                        :label="item.title"
                                        :value="item.rowId"
                                    ></el-option>
                                </el-select>
                            </el-col>
                            <!-- <el-col :span="2">
                                <span>角色：</span>
                            </el-col>
                            <el-col :span="3">
                                <el-select v-model="roleId2" placeholder="请选择角色" clearable>
                                    <el-option
                                        v-for="item in roleValue"
                                        :key="item.roleId"
                                        :label="item.roleName"
                                        :value="item.roleId"
                                    ></el-option>
                                </el-select>
                            </el-col> -->
                            <el-col :span="2" class="ml10">
                                <el-button type="primary" @click="getUserlist">查询结果</el-button>
                            </el-col>
                        </el-row>
                    </el-collapse-item>
                </el-collapse>
            </div>
            <div class="list_block">
                <div class="list_title clearfix">
                    <div class="list_l">
                        <i class="el-icon-tickets"></i>
                        <span>用户列表</span>
                    </div>
                    <div class="list_r">
                        <el-button @click="addUser">添加</el-button>
                    </div>
                </div>
                <el-table
                    :data="userList"
                    border
                    style="width:100%"
                    v-loading="loading"
                >
                    <el-table-column
                        prop="userNo"
                        label="用户帐号"
                        sortable
                    ></el-table-column>
                    <el-table-column
                        prop="userName"
                        label="姓名"
                        sortable
                    ></el-table-column>
                    <el-table-column
                        prop="dutyName"
                        label="职责"
                        sortable
                    ></el-table-column>
                    <!-- <el-table-column
                        prop="orgName"
                        label="所属组织"
                        sortable
                    ></el-table-column>
                    <el-table-column
                        prop="roleName"
                        label="角色"
                        width="100"
                        sortable
                    ></el-table-column> -->
                    <el-table-column
                        width="100"
                        label="下属人数"
                        sortable
                    >
                        <template slot-scope="scope">
                            <a @click="handleNum(scope)">{{scope.row.userNum}}</a>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="createTime"
                        label="创建日期"
                        sortable
                    ></el-table-column>
                    <el-table-column
                        label="是否启用"
                        width="80"
                    >
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.openFlag" @change="changeSwitch($event,scope)"></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作">
                        <template slot-scope="scope">
                            <a @click="edit(scope)" class="mr15">编辑</a>
                            <a @click="deleteRow(scope)" class="mr15">删除</a>
                            <a @click="resetPass(scope)">密码重置</a>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page_container">
                    <el-pagination
                        @current-change="handleCurrentChange"
                        :current-page.sync="currentPage"
                        :page-sizes="[5, 10, 15, 20]"
                        :page-size="threadNum"
                        layout="total, prev, pager, next, jumper"
                        :total="totleNum">
                    </el-pagination>                    
                </div>
            </div>
        </div>
        <div>
            <el-dialog
                :title="dialogTitle"
                :visible.sync="dialogVisible"
                width="40%"
            >
                <el-row class="mt20">
                    <el-col :span="6"><span><span class="red">*</span>用户帐号：</span></el-col>
                    <el-col :span="15">
                        <el-input v-model="userNo" placeholder="员工号" @blur="blurUser"></el-input>
                    </el-col>
                </el-row>
                <el-row class="mt20">
                    <el-col :span="6"><span>即时通讯帐号：</span></el-col>
                    <el-col :span="15">
                        <el-input v-model="imNo" placeholder="默认为用户帐号"></el-input>
                    </el-col>
                </el-row>
                <el-row class="mt20">
                    <el-col :span="6"><span><span class="red">*</span>用户姓名：</span></el-col>
                    <el-col :span="15">
                        <el-input v-model="userName"></el-input>
                    </el-col>
                </el-row>
                <el-row class="mt20">
                    <el-col :span="6"><span>失效日期：</span></el-col>
                    <el-col :span="15">
                        <el-date-picker
                            v-model="expireTime"
                            type="date"
                            placeholder="选择日期">
                        </el-date-picker>
                    </el-col>
                </el-row>
                <el-row class="mt20">
                    <el-col :span="6"><span><span class="red">*</span>密码：</span></el-col>
                    <el-col :span="15">
                        <el-input placeholder="******" type="password" v-model="password"></el-input>
                    </el-col>
                </el-row>
                <el-row class="mt20">
                    <el-col :span="6"><span>邮箱地址：</span></el-col>
                    <el-col :span="15">
                        <el-input v-model="email" @blur="blurEmail"></el-input>
                        <p class="waring">{{waring}}</p>
                    </el-col>
                </el-row>
                <!-- <el-row class="mt20">
                    <el-col :span="6"><span><span class="red">*</span>所属组织：</span></el-col>
                    <el-col :span="15">
                        <el-select v-model="orgId" placeholder="请选择组织" clearable @focus="focusOrg">
                            <el-option
                                v-for="item in depValue"
                                :key="item.rowId"
                                :label="item.orgName"
                                :value="item.rowId"
                            ></el-option>
                        </el-select>
                    </el-col>
                </el-row> -->
                <el-row class="mt20">
                    <el-col :span="6"><span><span class="red">*</span>职责：</span></el-col>
                    <el-col :span="15">
                        <el-select v-model="dutyId" placeholder="请选择职责" clearable>
                            <el-option
                                v-for="item in dutyList"
                                :key="item.rowId"
                                :label="item.title"
                                :value="item.rowId"
                            ></el-option>
                        </el-select>
                    </el-col>
                </el-row>
                <el-row class="mt20">
                    <el-col :span="6"><span>主管姓名：</span></el-col>
                    <el-col :span="15">
                        <el-select v-model="managerId" placeholder="请选择主管" clearable @focus="focusManage"> 
                            <el-option
                                v-for="item in manageValue"
                                :key="item.userId"
                                :label="item.userName"
                                :value="item.userId"
                            ></el-option>
                        </el-select>
                    </el-col>
                </el-row>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editUser" :loading="btnloading">提 交</el-button>
                </span>
            </el-dialog>
            <el-dialog
                    title="密码重置"
                    :visible.sync="dialogVisible2"
                    width="30%"
                >
                    <el-input type="password" v-model="resetpass" placeholder="请输入新密码"></el-input>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible2 = false">取 消</el-button>
                        <el-button type="primary" @click="resetNewPass" :loading="btnloading2">确 定</el-button>
                    </span>
            </el-dialog>
        </div>
    </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
    data() {
        return {
           waring:"",
           resetpass:"",
           loading: false,
           btnloading: false,
           btnloading2: false,
           currentPage:1,
           activeNames: ['1'],
           search_input: "",
           chargeName:"",
           departInput:"",
           roleInput:"",
           showNum:"",
           showNumOptions: [{
               value: "5",
               label: '显示5条'
           },{
               value: "10",
               label: '显示10条'
           }],
           orderTypeOptions: [{
               value: "1",
               label: '正序'
           },{
               value: "-1",
               label: '倒序'
           }],
           orderType:"",
           dialogVisible: false,
           dialogVisible2: false,
           //添加员工所需字段
           rowId: null,
           userNo:"",
           imNo:"",
           userName:"",
           expireTime:"",
           password:"",
           email:"",
           orgId:"",
           roleId:"",
           managerId:"",
           dutyId:"",
           //添加及编辑的title
           dialogTitle:"",
           //搜索字段
           departmentId2: "",
           managerId2: "",
           roleId2:"",
           dutyId2: "",
           searchKey:"",
           //存在本地的每页条数
           threadNum: parseInt(localStorage.getItem('pagesize'))
        }
    },
    computed: mapState({
        msg: state => state.user.msg,
        depValue: state => state.depart.depList,
        roleValue: state => state.role.roleList,
        manageValue: state => state.user.userAllList,
        totleNum: state => state.user.totleNum,
        dutyList: state => state.depart.dutyList,
        userList(state) {
            let arr = [];
            state.user.userList.map((item) => {
                item.createTime = item.createTime ? this.formatDate(item.createTime):'';
                arr.push(item);
            });
            return arr;
        },
    }),
    methods: {
        verifyEmail(email) {
            let filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if(filter.test(email)) {
                return true;
            }else{
                return false;
            }
        },
        blurEmail() {
            if(this.email && this.email.length !== 0 && !this.verifyEmail(this.email)) {
                this.waring = "邮箱地址不正确";
            }else{
                this.waring = "";
            }
        },
        focusOrg() {
            this.getDepartList();
        },
        focusManage() {
            this.getAllUser();
        },
        handleNum(scope) {
            this.managerId2 = scope.row.userId;
            this.getUserlist();
        },
        resetPass(scope) {
            this.dialogVisible2 = true;
            localStorage.setItem('resetId',scope.row.userId);
        },
        resetNewPass() {
            if(this.resetpass == '') {
                this.$message('请输入新密码');
            }else{
                this.btnloading2 = true;
                this.$store.dispatch('resetPassword',{
                    userId: localStorage.getItem('resetId'),
                    password: this.resetpass,
                    sessionId: localStorage.getItem('sessionId')
                }).then(() => {
                    if(this.msg == '重置密码成功') {
                        this.btnloading2 = false;
                        this.dialogVisible2 = false;
                        this.$message(this.msg);
                    }else{
                        this.btnloading2 = false;
                        this.$message(this.msg);
                    }
                })
            }
        },
        handleCurrentChange(val) {
            this.loading = true;
            this.$store.dispatch('getUserList',{
                pageNo: val,
                pageSize: this.threadNum,
                searchKey: this.searchKey,
                managerId: this.managerId2,
                roleId: this.roleId2,
                orgId: this.departmentId2,
                sessionId: localStorage.getItem('sessionId')
            }).then(() => {
                this.loading = false;
            })
        },
        blurUser() {
            if(this.userNo !== "") {
                let flag = false;
                this.userList.map((item) => {
                    if(item.userNo == this.userNo) {
                        flag = true
                    }
                })
                if(flag) {
                    this.$message('该帐号已经存在，请更换其他帐号');
                }else{
                    this.imNo = this.userNo;
                }
            }
        },
        formatDate(d) {
            if (!!window.ActiveXObject || "ActiveXObject" in window) {
                return new Date(parseInt(d)).toLocaleString({hour12:false});
            }else if(navigator.userAgent.indexOf('Edge') > -1) {
                return new Date(parseInt(d)).toLocaleString({hour12:false});
            }else{
                return new Date(parseInt(d)).toLocaleString('chinese',{hour12:false});
            }
        },
        deleteRow(scope) {
            this.$confirm('确定删除？','提示',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                if(scope.row.userNum != 0) {
                    this.$message('该用户下有成员，不允许删除！');
                }else{
                    this.$store.dispatch('deleteUser',{
                        sessionId: localStorage.getItem('sessionId'),
                        contentId: scope.row.userId
                    }).then(() => {
                        this.$message(this.msg);
                        this.getUserlist();
                    })
                }
            }).catch((err) => {
                console.log(err);
            })
        },
        addDepart() {
            this.dialogVisible = true;
        },
        addUser() {
            this.dialogVisible = true;
            this.dialogTitle = "添加成员";
            this.rowId = null;
            //清空数据
            this.userNo = "";
            this.imNo = ""; 
            this.userName = "";
            this.expireTime = "";
            this.password = "";
            this.email = "";
            // this.orgId = "";
            // this.roleId = "";
            this.managerId = "";
            this.dutyId = "";
        },
        edit(scope) {
            this.dialogVisible = true;
            this.dialogTitle = "成员编辑";
            this.userNo = scope.row.userNo;
            this.imNo = scope.row.imNo;
            this.userName = scope.row.userName;
            this.expireTime = scope.row.expireTime;
            this.password = null;
            this.email = scope.row.email;
            // this.orgId = scope.row.orgId;
            // this.roleId = scope.row.roleId;
            this.managerId = scope.row.managerId;
            this.dutyId = scope.row.dutyId;
            this.rowId = scope.row.userId;
        },
        //编辑及添加人员
        editUser() {
            if(this.userNo == "") {
                this.$message('请输入用户帐号');
            }else if(this.depDesc == '') {
                this.$message('请输入职能描述');
            }else if(this.userName == '') {
                this.$message('请输入用户姓名');
            }else if(this.password == '') {
                this.$message('请输入密码');
            }else if(this.dutyId == '') {
                this.$message('请选择职责');
            }else if(this.rowId !== null){
                this.createNew();
            }else{
                this.createNew();
            }
        },
        //新建用户
        createNew() {
            this.btnloading = true;
            let obj = {
                userNo: this.userNo,
                imNo: this.imNo,
                userName: this.userName,
                expireTime: this.expireTime,
                password: this.password,
                email: this.email,
                // orgId: this.orgId,
                // roleId: this.roleId,
                dutyId: this.dutyId,
                managerId: this.managerId,
                rowId: this.rowId,
                sessionId: localStorage.getItem('sessionId')
            };
            this.$store.dispatch('createUser',obj).then(() => {
                if(this.msg == "保存成功") {
                    this.$message(this.msg);
                    this.btnloading = false;
                    this.dialogVisible = false;
                    this.getUserlist();
                }else{
                    this.btnloading = false;
                    this.$message(this.msg);
                }
            })
        },
        // //获取部门集合
        // getDepartList() {
        //     this.$store.dispatch('getDepAllList',{
        //         pageSize: -1,
        //         sessionId: localStorage.getItem('sessionId')
        //     })
        // },
        // //获取角色集合
        // getRolelist() {
        //     this.$store.dispatch('getAllRoleList',{
        //         pageSize: -1,
        //         sessionId: localStorage.getItem('sessionId')
        //     })
        // },
        //获取所有职责
        getAllDutyList() {
            this.$store.dispatch('getAllDutyList',{
                pageSize: -1,
                filter: true,
                sessionId: localStorage.getItem('sessionId')
            })
        },
        //获取主管集合
        getAllUser() {
            this.$store.dispatch('getAllUserList',{
                pageSize: -1,
                sessionId: localStorage.getItem('sessionId')
            })
        },
        //获取人员列表
        getUserlist() {
            this.$store.state.user.userList = [];
            this.loading = true;
            this.$store.dispatch('getUserList',{
                pageSize: this.threadNum,
                searchKey: this.searchKey,
                managerId: this.managerId2,
                dutyId: this.dutyId2,
                // roleId: this.roleId2,
                // orgId: this.departmentId2,
                sessionId: localStorage.getItem('sessionId')
            }).then(() => {
                if(this.msg !== '成功') {
                    this.loading = false;
                    this.$message(this.msg)
                }else{
                    this.loading = false;
                }
            })
        },
        //开启及关闭
        changeSwitch(event,scope) {
            if(event == true) {
                this.$store.dispatch('openUser',{
                    contentId: scope.row.userId,
                    sessionId: localStorage.getItem('sessionId')
                }).then(() => {
                    this.$message(this.msg);
                })
            }else{
                this.$store.dispatch('closeUser',{
                    contentId: scope.row.userId,
                    sessionId: localStorage.getItem('sessionId')
                }).then(() => {
                    this.$message(this.msg);
                })
            }
        }
    },
    created() {
        if(this.$route.params.orgId) {
            this.departmentId2 = this.$route.params.orgId;
            this.getUserlist();
        }else if(this.$route.params.roleId) {
            this.roleId2 = this.$route.params.roleId;
            this.getUserlist();
        }else if(this.$route.params.dutyId) {
            this.dutyId2 = this.$route.params.dutyId;
            this.getUserlist();
        }else{
            this.getUserlist();
        }
        this.getAllDutyList();
        //this.getDepartList();
        //this.getRolelist();
        this.getAllUser();
    }
}
</script>
<style scoped>
.search_block >>> .el-collapse-item__header{
    padding: 0 15px;
    border: 1px solid #ebeef5;
    border-top: none;
    background-color:#eee;
}
.search_block >>> .el-collapse-item__content{
    border: 1px solid #ebeef5;
    border-bottom: none;
    border-top: none;
    padding-top: 20px;
    padding-bottom: 20px;
}
.custom-5a6775 .el-collapse-item__arrow{
    margin: 0;
}
.pleft{
    margin-left:1px;
}
.list_block{
    margin-top: 10px;
}
.list_l{
    float: left;
}
.list_title{
    height: 48px;
    line-height: 48px;
    background-color: #eee;
    padding: 0 15px;
    font-size: 13px;
}
.list_r{
    float: right;
}
.el-table .cell {
    height: 23px;
}
.mr20{
    margin-right: 20px;
}
.el-table th>.cell{
    height: 22px;
}
.waring{
    color: red;
    font-size: 12px;
}
</style>


